<?php
/*
 * @Author: 孙开源 && sunkaiyuan@namenode.cn
 * @Date: 2023-04-12 16:45:39
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @LastEditTime: 2023-04-18 15:42:22
 * @Description: 
 * 
 */

namespace zhijingfeisuo\Kernel\Services;

use Psr\SimpleCache\CacheInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Psr16Cache;


class Cacher
    {
    /**
     * @var \zhijingfeisuo\Application
     */
    protected $app;
    /**
     * cache 驱动
     * @var \Psr\SimpleCache\CacheInterface
     */
    protected $cacherDriver;

    /**
     * @return \Psr\SimpleCache\CacheInterface
     */
    /**
     * Logger constructor.
     *
     * @param \zhijingfeisuo\Application
     */
    public function __construct($app)
        {
        $this->app = $app;
        }
    public function getCache()
        {
        if ($this->cacherDriver) {
            return $this->cacherDriver;
            }

        if (property_exists($this, 'app') && $this->app->offsetExists('cache') && ($this->app['cache'] instanceof CacheInterface)) {
            return $this->cacherDriver = $this->app['cache'];
            }

        return $this->cacherDriver = $this->createDefaultCache();
        }

    public function __call($name, $a)
        {
        if ($this->cacherDriver == null)
            $this->cacherDriver = $this->getLogger();
        //调用重新的方法
        if (method_exists($this, "_r{$name}")) {
            $callf = "_r{$name}";
            return $this->$callf(...$a);
            }
        else
            return $this->cacherDriver->$name(...$a);

        }
    public function setCache($cache)
        {
        $this->cacherDriver = $cache;
        }
    /**
     * @description:缓存 Key
     * @return string 
     */
    protected function cacheFor($name)
        {
        return sprintf('zhijing_access_token.%s', $name);
        }
    /**
     * @description: 默认缓存
     * @return \Psr\SimpleCache\CacheInterface
     */
    protected function createDefaultCache() : \Psr\SimpleCache\CacheInterface
        {
        if (class_exists(Psr16Cache::class)) {
            return new Psr16Cache(new FilesystemAdapter('zhijingfeisuo'));
            }
        }


    public function _rget($key, $default = null)
        {
        $newkey = $this->cacheFor($key);
        return $this->cacherDriver->get($newkey, $default);
        }


    public function _rset($key, $value, $ttl = null)
        {
        $newkey = $this->cacheFor($key);
        return $this->cacherDriver->set($newkey, $value, $ttl);
        }


    public function _rdelete($key)
        {
        $newkey = $this->cacheFor($key);
        return $this->cacherDriver->delete($newkey);
        }


    public function _rhas($key)
        {
        $newkey = $this->cacheFor($key);
        return $this->cacherDriver->has($newkey);
        }

    }